package com.wzm.service.impl;

import com.wzm.domain.Move;
import com.wzm.domain.User;
import com.wzm.domain.UserMove;
import com.wzm.mapper.MoveMapper;
import com.wzm.service.MoveService;
import com.wzm.util.Ajaxresult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Random;
import java.util.stream.LongStream;

@Service
public class MoveServiceImpl implements MoveService {
    @Autowired
    private MoveMapper moveMapper;

    @Override
    public List<Move> findAll() {
        return moveMapper.findAll();
    }

    @Override
    public Move findById(Long id) {
        return moveMapper.findById(id);
    }

    @Override
    @Transactional
    public Ajaxresult buyById(UserMove userMove) {
        Move move = moveMapper.findById(userMove.getMovie_ticket_id());
        move.setStock(move.getStock() - 1);
        moveMapper.update(move);
        userMove.setStatus(0);
        moveMapper.add(userMove);
        return new Ajaxresult(true, "购买成功", move.getPrice());
    }

    @Override
    public Ajaxresult sendTicket(User user) {
        Long id = user.getId();
        UserMove userMove = new UserMove();
        userMove.setUser_id(id);
        Random random = new Random();
        Long longs = random.nextLong();
        Move byId = moveMapper.findById(longs);
        if (byId == null) {
            return new Ajaxresult(false, "很遗憾", "您未抽中免费票");
        }
        userMove.setMovie_ticket_id(longs);
        moveMapper.add(userMove);
        return new Ajaxresult();
    }

    @Override
    public Ajaxresult watch(Long id) {
        List<UserMove> userMove = moveMapper.findStatusByTicketId(id);
        if (userMove == null) {
            return new Ajaxresult(false, "您未购买", "请重新购票");
        }
        for (UserMove um : userMove) {
            if(um.getStatus()==1){
                moveMapper.del(um.getMovie_ticket_id(),um.getStatus());
            }
        }
        for (UserMove um : userMove) {
            um.setStatus(1);
            moveMapper.updateUserMove(um);
        }
        return new Ajaxresult(true, "电影观看结束", "祝您生活愉快");
    }
}
